package jw.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import jw.hospital.hosp.model.hospital.Department;
import jw.hospital.hosp.vo.DepartmentQueryVo;
import jw.hospital.respository.DepartmentRespository;
import jw.hospital.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/*
 *@Author Mark Lee
 *@Date 2021/8/31 15:29
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRespository  departmentRespository;

    @Override
    public void save(Map<String, Object> paramMap) {
        String paramMapString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramMapString, Department.class);
        Department  departmentExist = departmentRespository.getDepartByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());
        if(departmentExist!=null) {//存在 更新
            department.setUpdateTime(new Date());
            department.setIsDeleted("0");
            departmentRespository.save(department);
        }else { //不存在 新增
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted("0");
            departmentRespository.save(department);
        }

    }


    @Override
    public Page<Department> findPageDeptment(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        Pageable pageable = PageRequest.of(page-1, limit, Sort.Direction.DESC);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Department department =new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        Example example = Example.of(department,matcher);
        Page all = departmentRespository.findAll(example, pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRespository.getDepartByHoscodeAndDepcode(hoscode, depcode);
        if(department!=null){
            departmentRespository.deleteById(department.getId());
        }
    }


}
